package ptoVenta;

import java.sql.*;
import javax.swing.JOptionPane;
import java.util.Calendar;

/**
 *
 * @author kirby joel del toro reyes
 */
public class sesion extends javax.swing.JFrame {

    public sesion() {
        initComponents();
        Calendar cal = Calendar.getInstance();
        String fecha = cal.get(cal.YEAR) + "/" + cal.get(cal.MONTH) + "/" + cal.get(cal.DATE);
        String hora = cal.get(cal.HOUR_OF_DAY) + ":" + cal.get(cal.MINUTE) + ":" + cal.get(cal.SECOND);
        this.jlbFecha.setText(fecha);
        this.jlbHora.setText(hora);
        jtfUsuario.requestFocus();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jlbUsuario = new javax.swing.JLabel();
        jlbContrasena = new javax.swing.JLabel();
        jtfUsuario = new javax.swing.JTextField();
        jbtSesion = new javax.swing.JButton();
        jlbIniSesion = new javax.swing.JLabel();
        jtfContrasena = new javax.swing.JPasswordField();
        jlbFecha = new javax.swing.JLabel();
        jlbHora = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jPanel1.setBackground(new java.awt.Color(-4144960,true));

        jlbUsuario.setBackground(new java.awt.Color(-16776961,true));
        jlbUsuario.setFont(new java.awt.Font("Serif", 1, 24));
        jlbUsuario.setForeground(new java.awt.Color(-16776961,true));
        jlbUsuario.setText("USUARIO");

        jlbContrasena.setFont(new java.awt.Font("Serif", 1, 24));
        jlbContrasena.setForeground(new java.awt.Color(-16776961,true));
        jlbContrasena.setText("CONTRASEÑA");

        jbtSesion.setFont(new java.awt.Font("Serif", 1, 18));
        jbtSesion.setForeground(new java.awt.Color(-16776961,true));
        jbtSesion.setText("OK!");
        jbtSesion.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtSesionActionPerformed(evt);
            }
        });

        jlbIniSesion.setFont(new java.awt.Font("Serif", 1, 18));
        jlbIniSesion.setForeground(new java.awt.Color(-16776961,true));
        jlbIniSesion.setText("Iniciar Sesion");

        jlbFecha.setText("FECHA:");

        jlbHora.setText("HORA:");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jlbUsuario)
                                    .addComponent(jlbContrasena))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(jtfUsuario, javax.swing.GroupLayout.DEFAULT_SIZE, 249, Short.MAX_VALUE)
                                    .addComponent(jtfContrasena, javax.swing.GroupLayout.DEFAULT_SIZE, 249, Short.MAX_VALUE)))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jlbFecha, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(138, 138, 138)
                                .addComponent(jlbHora, javax.swing.GroupLayout.DEFAULT_SIZE, 151, Short.MAX_VALUE)))
                        .addContainerGap())
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jlbIniSesion)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 161, Short.MAX_VALUE)
                        .addComponent(jbtSesion)
                        .addGap(96, 96, 96))))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(43, 43, 43)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jlbUsuario)
                    .addComponent(jtfUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jlbContrasena)
                    .addComponent(jtfContrasena, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(44, 44, 44)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jlbIniSesion)
                    .addComponent(jbtSesion))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jlbFecha, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jlbHora, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(20, 20, 20))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jbtSesionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtSesionActionPerformed
        try {
            //chekar si el usuario escrbio el nombre de usuario y pw
            if (jtfUsuario.getText().length() > 0 && jtfContrasena.getText().length() > 0) {
                // Si el usuario si fue validado correctamente
                if (validarUsuario(jtfUsuario.getText(), jtfContrasena.getText())) //enviar datos a validar
                {
                    // Codigo para mostrar la ventana principal
                    setVisible(false);
                    ventas mod = new ventas();
                    mod.setLocationRelativeTo(null);
                    mod.setVisible(true);
                } else {
                    JOptionPane.showMessageDialog(null, "El nombre de usuario y/o contrasenia no son validos.");
                    JOptionPane.showMessageDialog(null, jtfUsuario.getText() + " " + jtfContrasena.getText());
                    jtfUsuario.setText("");    //limpiar campos
                    jtfContrasena.setText("");
                    jtfUsuario.requestFocusInWindow();
                    jtfUsuario.requestFocus();
                }
            } else {
                JOptionPane.showMessageDialog(null, "Debe escribir nombre de usuario y contrasenia.\n"
                        + "NO puede dejar ningun campo vacio");
                jtfUsuario.requestFocus();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }//GEN-LAST:event_jbtSesionActionPerformed
    private boolean validarUsuario(String elUsr, String elPw) {
        try {

            Connection Conexion = DriverManager.getConnection("jdbc:postgresql://localhost:5432/punto_venta", "postgres", "12345");
            PreparedStatement consultasql = Conexion.prepareStatement("select * from usuarios where puesto=? AND contrasena=?");
            ResultSet resultadosql;
            consultasql.setString(1, elUsr);
            consultasql.setString(2, elPw);

            resultadosql = consultasql.executeQuery();
            resultadosql.next();
            String correo = resultadosql.getString(1);
            String contrasena = resultadosql.getString(2);
            if (correo.length() > 0 && contrasena.length() > 0) //if( resultadosConsulta.first() )        // si es valido el primer reg. hay una fila, tons el usuario y su pw existen
            {
                return true;        //usuario validado correctamente
            } else {
                return false;        //usuario validado incorrectamente
            }
        } catch (SQLException e) {
            // e.printStackTrace();
            return false;
        }
    }

    public static void main(String arg[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(sesion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(sesion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(sesion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(sesion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new sesion().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel jPanel1;
    private javax.swing.JButton jbtSesion;
    private javax.swing.JLabel jlbContrasena;
    private javax.swing.JLabel jlbFecha;
    private javax.swing.JLabel jlbHora;
    private javax.swing.JLabel jlbIniSesion;
    private javax.swing.JLabel jlbUsuario;
    private javax.swing.JPasswordField jtfContrasena;
    public static javax.swing.JTextField jtfUsuario;
    // End of variables declaration//GEN-END:variables
}
